package newview;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * 股票的最大利润
 * 可以有一次买入和一次卖出，买入必须在前。求最大收益。
 * @author TANGYE
 * @date 2021/7/25 9:53 上午
 **/
public class Maigupiao {

    /**
     * 一次股票买卖最大收益
     * @param prices 股票价格
     * @return
     */
    public static Double getMaxProfitOnce(double[] prices) {
        if (null == prices || prices.length == 0) {
            return 0.00;
        }
        double maxProfit = 0;
        double minPrice = prices[0];
        for (int i = 1; i < prices.length; i++) {
            minPrice = Double.min(minPrice, prices[i]);
            maxProfit = Double.max(maxProfit, prices[i] - minPrice);
        }
        return maxProfit;
    }

    /**
     * 多次买入卖出， 只要T+1日的价格大于T日的价格， 就可以买卖获取收益
     * @param prices
     * @return
     */
    public static Double getMaxProfitMore(double[] prices) {
        double maxProfit = 0;

        for (int i = 1; i < prices.length; i++) {
            if (prices[i] > prices[i-1]) {
                maxProfit += prices[i] - prices[i-1];
            }
        }

        return maxProfit;
    }

    public static void main(String[] args) {
        double[] prices = new double[] {1.00, 1.54, 1.49, 1.65};
        System.out.println(new BigDecimal(getMaxProfitOnce(prices).doubleValue()).setScale(2, BigDecimal.ROUND_HALF_UP));

        double[] prices1 = new double[] {1,3,2,5,8,6,5,7};
        System.out.println(getMaxProfitMore(prices1));

    }
}
